from asyncio import start_server, StreamReader, StreamWriter
from asyncio.base_events import Server
from typing import Optional

"""
    rpc流服务器
"""


class StreamServer(object):
    def __init__(self, ip: str, port: int, name: Optional[str] = None):
        self.ip = ip
        self.port = port
        self.address = f"{self.ip}:{self.port}"
        self._name = name
        self.main_server: Optional[Server] = None

        if self._name is None:
            self._name = type(self).__name__

    async def _run(self):
        print(f"{self._name} {self.address} 启动成功")
        self.main_server = await start_server(self.handle, self.ip, self.port)
        try:
            async with self.main_server:
                await self.main_server.serve_forever()
        except RuntimeError:
            pass
        finally:
            await self.on_close()

    async def run(self) -> None:
        """启动"""
        await self._run()

    async def handle(self, reader: StreamReader, writer: StreamWriter) -> None:
        """conn链接"""
        # conn = Conn(reader, writer)
        try:
            while data := await reader.read(1024):
                if not data:
                    break
                await self.on_message(data)
        except ConnectionError:
            print("客户端断开连接")
        except Exception as e:
            print(f"{self._name}.handle error==>{e}")
        finally:
            pass

    async def on_message(self, msg: bytes):
        """消息处理"""
        pass

    async def on_close(self):
        pass
